package com.etc.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.FullHttpMessage;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;


/**
 * @Author kalista
 * @Description
 * @Date 2021/5/27  17:34
 **/
public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
        System.out.println("收到消息:"+textWebSocketFrame.text());
        ctx.channel().writeAndFlush(new TextWebSocketFrame("WebSocket服务端在"));

    }



    // 建立连接
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channelGroup.add(ctx.channel());
        // json    {"all":12,"number":90}
        ctx.channel().writeAndFlush(new TextWebSocketFrame("sadfsdf"));
    }


    // 与客户端断开连接 通道关闭
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("关闭");
    }

    //读客户端得信息
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        System.out.println("督导了");
//        ctx.channel().writeAndFlush(new TextWebSocketFrame("sdf"));
////        FullHttpRequest fullHttpRequest = (FullHttpRequest)msg;
////        fullHttpRequest.

        while (true){
            channelGroup.writeAndFlush(new TextWebSocketFrame("我发了"));
            Thread.sleep(5000);
        }
    }



}
